<template>
  <div class="center">
    <div style="text-align:right">
      <el-button type="info" icon="el-icon-close" circle @click="closeButton"></el-button>
    </div>
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="售后联络人"></el-step>
      <el-step title="物流信息"></el-step>
      <el-step title="售后产品明细"> </el-step>
    </el-steps>

    <div class="main flex flex_cen">
      <el-form :model="addForm" ref="ruleForm" style="width:90%">
        <!-- 售后联络人start -->
        <div v-show="active == 0">
          <el-form-item label="代理商选择:" label-width="140px" prop="pId">
            <el-select v-model="addForm.pId" placeholder="没有选中任何项">
              <el-option v-for="item in lotoptions" :key="item.id" :label="`${item.username} : ${item.realname}`" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名:" label-width="140px" prop="name">
            <el-input v-model="addForm.name" autocomplete="off" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="手机号码:" label-width="140px" prop="phone">
            <el-input v-model="addForm.phone" autocomplete="off" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item label="地址:" label-width="140px" prop="address">
            <el-input v-model="addForm.address" autocomplete="off" placeholder="请输入地址"></el-input>
          </el-form-item>
        </div>
        <!-- 售后联络人end -->

        <!-- 物流信息start -->
        <div v-show="active == 1">
          <el-form-item label="快递公司:" label-width="140px" prop="mailExpress">
            <el-input v-model="addForm.mailExpress" autocomplete="off" placeholder="请输入快递公司"></el-input>
          </el-form-item>
          <el-form-item label="快递单号:" label-width="140px" prop="mailOrderNo">
            <el-input v-model="addForm.mailOrderNo" autocomplete="off" placeholder="请输入快递单号"></el-input>
          </el-form-item>
        </div>
        <!-- 物流信息end -->

        <!-- 售后产品明细start -->
        <div v-show="active == 2">
          <div class="addSale">
            <el-form size="mini" :model="newSolt" ref="addSale">
              <div class="flex flex_bet flex-wrap">
                <el-form-item label="产品条码SN:" label-width="100px" class="boxitem">
                  <el-input autocomplete="off" placeholder="请输入产品条码SN" v-model="newSolt.sn"></el-input>
                </el-form-item>
                <el-form-item label="产品型号:" label-width="90px" class="boxitem">
                  <div class="flex model setting">
                    <el-input autocomplete="off" placeholder="请先输入SN" v-model="newSolt.productModel" disabled></el-input>
                    <div class="modelButton">
                      <el-button size="mini " @click="inquireSn">查询</el-button>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="故障类别:" label-width="90px" class="boxitem">
                  <el-select placeholder="没有选中任何项" v-model="newSolt.faultType" size="mini">
                    <el-option v-for="item in fault" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否需要分析报告:" label-width="140px" class="boxitem">
                  <el-select placeholder="没有选中任何项" v-model="newSolt.isAnalyse" size="mini">
                    <el-option v-for="item in analyse" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="flex flex_bet felx_align">
                <el-form-item label="故障描述:" label-width="100px" class="boxitem" style="flex:1">
                  <el-input autocomplete="off" type="textarea" :rows="1" placeholder="请输入故障描述" v-model="newSolt.faultRemark"></el-input>
                </el-form-item>
                <div style="margin-left:20px;margin-bottom: 18px;">
                  <el-button type="primary" size="mini" @click="addInfo">添加</el-button>
                </div>
              </div>
            </el-form>
          </div>
          <div class="flex flex_bet" style="margin-top:20px">
            <div class="flex">
              <upload-excel-component :on-success="handleSuccess" />
              <el-button type="info" size="mini" @click="handleDownload" style="margin-left:10px">
                上传模板<i class="iconfont iconmobanxiazai" style="font-size:12px;height:0;display: inline-block;"></i>
              </el-button>
            </div>
          </div>
          <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:40px;" size="mini">
            <el-table-column prop="productModel" label="产品型号" min-width="160" align="center">
              <template slot-scope="scope">
                <span style="margin-right:10px">{{scope.row.productModel}}</span>
                <el-button size="mini" @click="getsnGetProductModel(scope.row.sn,scope.$index)">查询</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="sn" label="产品条码SN" min-width="160" align="center"></el-table-column>
            <el-table-column prop="faultType" label="故障类别" min-width="100" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.faultType" placeholder="没有选中任何项" size="mini">
                  <el-option v-for="item in fault" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="faultRemark" label="故障描述" min-width="160" align="center"></el-table-column>
            <el-table-column prop="isAnalyse" label="是否需要分析报告" min-width="100" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.isAnalyse" placeholder="没有选中任何项" size="mini">
                  <el-option v-for="item in analyse" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="60" align="center">
              <template slot-scope="scope">
                <el-row>
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 售后产品明细end -->
      </el-form>
    </div>
    <div class="next" style="margin-top:20px">
      <el-button style="margin-top: 12px;" @click="last" v-if="stepShow">上一步</el-button>
      <el-button style="margin-top: 12px;" @click="next" v-if="submitShow">下一步</el-button>
      <el-button style="margin-top: 12px;" type="primary" @click="getaddAfterSales" v-else>提交</el-button>
    </div>
  </div>
</template>

<script>
import { getUsernameInfo, getCommonUser, snGetProductModel, addAfterSales } from "@/api/aftersale.js";
import UploadExcelComponent from './uploadExcel.vue'
export default {
  components: { UploadExcelComponent },
  data() {
    return {
      active: 0,
      lotoptions: [],
      fault: [{ id: 1, name: '显示异常' }, { id: 2, name: '触摸异常' }, { id: 3, name: '充电异常' }, { id: 4, name: '摄像头异常' }, { id: 5, name: '喇叭异常' }, { id: 6, name: '耳机异常' },
      { id: 7, name: '卡开机画面' }, { id: 8, name: '无法开机' }, { id: 9, name: '客户误判' }, { id: 10, name: '其他' }],
      analyse: [{ id: 1, name: '是' }, { id: 0, name: '否' }],
      addForm: { pId: '', name: '', phone: '', address: '', afterSales: '', mailExpress: '', mailExpress: '' },
      tableData: [],
      tableHeader: ["产品型号", "产品条码SN", "故障类别", "故障描述", "是否需要分析报告"],
      newSolt: { sn: '', productModel: '', faultType: '', isAnalyse: 0, faultRemark: '' },
    }
  },
  created() {
    this.getUsernameInfos()
    this.getCommonUsers()
  },
  computed: {
    submitShow() {
      return this.active > 1 ? false : true
    },
    stepShow() {
      return this.active == 0 ? false : true
    }
  },
  methods: {
    next() {
      if (this.active++ > 1) this.active = 0;
    },
    last() {
      if (this.active > 0) this.active--;
    },
    handleSuccess({ results, header }) {
      var newArr = results.map(item => ({
        sn: item.产品条码SN,
        faultRemark: item.故障描述,
        productModel: '',
        faultType: '',
        isAnalyse: 0
      }))
      this.tableData = newArr
      console.log('===========表格数据', this.tableData)
    },
    //申请售后
    getaddAfterSales() {
      let addForm = JSON.parse(JSON.stringify(this.addForm))
      addForm.userId = localStorage.getItem("ID")
      addForm.last_ip = sessionStorage.getItem("Ip")
      addForm.afterSales = JSON.stringify(this.tableData)
      console.log('申请售后', addForm)
      addAfterSales(addForm).then(res => {
        this.$message.success(res.msg)
        this.$emit('closeFill')
      }).catch(err => {

      })
    },
    closeButton() {
      this.$emit('closeFill')
    },
    //添加单条数据
    addInfo() {
      let arr = this.tableData.map(item => item.sn)
      if (arr.includes(this.newSolt.sn)) {
        this.$message.error('该售后产品已添加，请勿重复添加')
      } else {
        this.tableData.push({
          sn: this.newSolt.sn,
          productModel: this.newSolt.productModel,
          isAnalyse: this.newSolt.isAnalyse,
          faultType: this.newSolt.faultType,
          faultRemark: this.newSolt.faultRemark
        })
        this.newSolt = { sn: '', productModel: '', faultType: '', isAnalyse: 0, faultRemark: '' }
      }
      console.log('------添加数据', this.tableData, arr)
    },
    //删除单条数据
    handleDelete(index) {
      this.tableData.splice(index, 1)
    },
    //sn码获取产品型号'
    getsnGetProductModel(sn, index) {
      console.log('传过来', sn, index)
      snGetProductModel({ sn: sn }).then(res => {
        this.tableData[index].productModel = res.data
      }).catch(err => {
        this.$message.error('查询无此型号')
        this.tableData[index].productModel = ''
      })
    },
    //单条sn获取型号
    inquireSn() {
      snGetProductModel({ sn: this.newSolt.sn }).then(res => {
        this.newSolt.productModel = res.data
      }).catch(err => {
        console.log('查询不到', err)
        this.$message.error('查询无此型号')
        this.newSolt.productModel = ''
      })
    },
    //获取代理商用户信息.1572.1502.1343.1204.1386.47.50
    getUsernameInfos() {
      getUsernameInfo({ userId: localStorage.getItem("ID") }).then(res => {
        this.lotoptions = res.data
        console.log('------代理商', res.data)
      }).catch(err => {
        this.lotoptions = []
      })
    },
    //获取账号常用联系人
    getCommonUsers() {
      getCommonUser({ userId: localStorage.getItem("ID") }).then(res => {
        Object.keys(this.addForm).forEach(key => { this.addForm[key] = res.data[key] })
      }).catch(err => {

      })
    },
    //批次创立更新导入模板
    handleDownload() {
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["产品条码SN", "故障描述"];
        const filterVal = ["产品条码SN", "故障描述"];
        const list = [{ "产品条码SN": 'QNS2HBYS0009', "故障描述": '机子画面卡' }]
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: '售后上传模板' });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
}
</script>

<style scoped>
/deep/ .el-step__head.is-success {
  color: #409eff;
  border-color: #409eff;
}
/deep/ .el-step__title.is-success {
  color: #409eff;
}
</style>

<style scoped lang="scss">
.main {
  margin-top: 40px;
}
.next {
  display: flex;
  justify-content: center;
}
.addSale {
  margin-top: 20px;
  .saliInput {
    width: 20%;
  }
}
.model {
  position: relative;
  .modelButton {
    position: absolute;
    right: 5px;
    button {
      padding: 2px 10px;
    }
  }
}
</style>